<?php
/**
 * OrangeHRM is a comprehensive Human Resource Management (HRM) System that captures
 * all the essential functionalities required for any enterprise.
 * Copyright (C) 2006 OrangeHRM Inc., http://www.orangehrm.com
 *
 * OrangeHRM is free software; you can redistribute it and/or modify it under the terms of
 * the GNU General Public License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * OrangeHRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program;
 * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA
 *
 */
require_once ROOT_PATH . '/lib/confs/Conf.php';
require_once ROOT_PATH . '/lib/confs/sysConf.php';
require_once ROOT_PATH . '/lib/models/time/Timesheet.php';
require_once ROOT_PATH . '/lib/models/time/TimeEvent.php';
require_once ROOT_PATH . '/lib/models/time/ProjectReport.php';
require_once ROOT_PATH . '/lib/common/TemplateMerger.php';

require_once ROOT_PATH . '/lib/models/time/AttendanceRecord.php';
require_once ROOT_PATH . '/lib/extractor/time/EXTRACTOR_AttendanceRecord.php';

require_once ROOT_PATH . '/lib/models/attendance/AttendanceStatistics.php';

class AttendanceController {



	var $AttendanceCache;
	var $objTime;
	var $id;
	var $authorizeObj;
	var $db = "";
	var $wilteList = "";
	var $SpAdList = "";
	var $SpAdRecordList = "";
	var $newwiletlist = "";
	var $RuleValue = "";
	var $LunRuleValue = "";
	var $WeekHolidays = "";
	var $Statczt = "";
	var $StatOt = "";

	public function setObjTime($objTime) {
		$this->objTime=$objTime;
	}

	public function getObjTime() {
		return $this->objTime;
	}

	public function setId($id) {
		$this->id=$id;
	}

	public function getId() {
		return $this->id;
	}

	public function __construct() {
		include(ROOT_PATH . '/customConfig/attendance.config.php');
		$this->AttendanceCache = $_CfgAttendance;
		$this->db = new DMLFunctions();
		error_reporting(0);
	}

	public function __distruct() {
		$this->db->dbDisconnect();
	}
	
	//获取考勤配置
	public function getRuleValue($rulekey = "AttendanceRule",$key = "") {
		//static $RuleValue = null;
		//if ($RuleValue === null) {
			$sql = "select * from hs_hr_sysconfigs where `key`='{$rulekey}'";
			$query = $this->db->executeQuery($sql);
			$result = mysql_fetch_array($query, MYSQL_ASSOC);
			if($result['value'] != "") {
				$RuleValue = unserialize($result['value']);
			} else {
				$RuleValue = array();
			}
		//}
		
		if($key != "") {
			return $RuleValue[$key];
		} else {
			return $RuleValue;
		}
	}
	/**
	 *考勤规则显示 
	 **/
	public function ShowAttendanceRule() {
		$records = $this->getRuleValue();
		//print_r($records);
		//die();
		$path = "/templates/attendance/ShowAttendanceRule.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}

	/**
	 *考勤规则保存 
	 **/
	public function SaveAttendanceRule() {
		
		$value = serialize($_POST);
		//保存数据
		
		$sql = "select * from hs_hr_sysconfigs where `key`='AttendanceRule'";
		$query = $this->db->executeQuery($sql);
		$records = mysql_fetch_array($query, MYSQL_ASSOC);
		if($records == "") {
			$sql = "insert into  hs_hr_sysconfigs (`key`,`value`,`addtime`) values ('AttendanceRule','{$value}',".time().")";
			$resulq = $this->db->executeQuery($sql);
		} else {
			$sql = "update hs_hr_sysconfigs set  `value` = '{$value}' where `key`='AttendanceRule'";
			$resulq = $this->db->executeQuery($sql);
		}
		$this->redirect("保存成功", "?adcode=attendrule");
	}


	/**
	 *导入考勤原始记录 
	 **/
	public function ShowExcelUpload() {
		$records = array();
		$path = "/templates/attendance/ExcelUpload.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}
	
	
	/**
	 *保存导入的考勤原始记录 
	 **/
	public function SaveExcelUpload() {
		//require_once ROOT_PATH . '/lib/extend/excel_class.php';
		require_once ROOT_PATH . '/lib/extend/Excel/reader.php';
		//查出所有员工的卡号和员工id相对应
		$empArr = array();
		$empArr2 = array();
		$empArr3 = array();
		$sql = "select emp_number,employee_id,emp_firstname,emp_attend_card_no from hs_hr_employee";
		$query = $this->db->executeQuery($sql);
		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			if($row['emp_attend_card_no'] != "") {
				if(strstr($row['emp_attend_card_no'],',')) {
					$noarr = explode(',',$row['emp_attend_card_no']);
					foreach ($noarr as $k => $v) {
						$empArr[$v] = $row['emp_number'];
					}
				} else {
					$empArr[$row['emp_attend_card_no']] = $row['emp_number'];
				}
			}
			$empArr2[$row['employee_id']] = $row['emp_number'];
			$empArr3[$row['emp_firstname']] = $row['emp_number'];
		}
		
		//获取所有的打卡记录
		$IsMenuText = isset($_POST['IsMenuText'])?intval($_POST['IsMenuText']):'';
		$RecordDateLie = isset($_POST['RecordDate'])?intval($_POST['RecordDate']):5;
		$RecordTimeLie = isset($_POST['RecordTime'])?intval($_POST['RecordTime']):6;
		$MachineNumLie = isset($_POST['MachineNum'])?intval($_POST['MachineNum']):8;
		$EmpCardNumLie = isset($_POST['EmpCardNum'])?intval($_POST['EmpCardNum']):2;
		$EmpIdNumLie = isset($_POST['EmpIdNum'])?intval($_POST['EmpIdNum']):3;
		$dataTem = new Spreadsheet_Excel_Reader();
		$dataTem->setOutputEncoding('utf-8');
		$dataTem->read($_FILES['upload']['tmp_name']);
		$date = $dataTem->sheets[0];
		//Read_Excel_File($_FILES['upload']['tmp_name'],$return);
		//$date = isset($return['Sheet 1'])?$return['Sheet 1']:$return['Sheet1'];
		$atdate = $date['cells'];
		/*echo "dfdf";
		echo "<pre>";
		print_r($date);
		die();*/
		if($IsMenuText == 1) $st = 2;
		else $st = 1;
		$sqlArr = array();
		$where = "";
		$nowtime = time();
		for ($i=$st;$i<=$date['numRows'];$i++)
		{
			$EmpCardNum = intval($atdate[$i][$EmpCardNumLie]);
			$MachineNum = intval($atdate[$i][$MachineNumLie]);
			$EmpIdNum = intval($atdate[$i][$EmpIdNumLie]);
			//$tem = explode('.',$atdate[$i][$RecordTimeLie]);
			//echo $atdate[$i][$RecordTimeLie]."<br>";
			
			$RecordTime = intval(strtotime($atdate[$i][$RecordDateLie]." ".$atdate[$i][$RecordTimeLie]));//strtotime($tem[0]);

			$EmpId = isset($empArr[$EmpCardNum])?$empArr[$EmpCardNum]:(isset($empArr2[$EmpIdNum])?$empArr2[$EmpIdNum]:(isset($empArr3[$atdate[$i][4]])?$empArr3[$atdate[$i][4]]:$EmpIdNum));
			$where .= "(MachineNum = '{$MachineNum}' and EmpCardNum = '{$EmpCardNum}' and RecordTime = '{$RecordTime}') or ";
			$sqlArr[$MachineNum."-".$EmpCardNum."-".intval($RecordTime)] = "('".$EmpId."','".$MachineNum."','".$EmpCardNum."','1','".@date('Y',$RecordTime)."','".@date('m',$RecordTime)."','".@date('d',$RecordTime)."','".$RecordTime."',".$nowtime.")";
		}
		if($where != "") $where = " where ".$where;
		$where = rtrim($where,"or ");
		$sql = "select MachineNum,EmpCardNum,RecordTime from hs_hr_emp_attendance {$where}";
		$query = $this->db->executeQuery($sql);
		$addnum = count($sqlArr);
		$allnum = $addnum;
		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			unset($sqlArr[$row['MachineNum']."-".$row['EmpCardNum']."-".$row['RecordTime']]);
			$addnum--;
		}
			/*echo "<pre>";
			print_r($sqlArr);
			die();*/
		if (count($sqlArr) > 0) {
			$sqlstr = implode(',',$sqlArr);
			$sql = "insert into hs_hr_emp_attendance(EmpId,MachineNum,EmpCardNum,Classes,Year,Month,Day,RecordTime,AddTime) values{$sqlstr}";
			$isok = $this->db->executeQuery($sql);
		}
		
		
		$records['addnum'] = $addnum;
		$records['allnum'] = $allnum;
		$records['AddTime'] = @date("Y-m-d H:i:s",$nowtime);
		$path = "/templates/attendance/ExcelUpload.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}
	
	
	
	
	/**
	 *批量删除某时刻的考勤原始记录 
	 **/
	public function DeleteExcelUpload() {
	
		//获取所有的打卡记录
		$AddTime = intval(strtotime($_POST['AddTime']));
		
		/*echo $AddTime;
		die();*/
		if($AddTime > 0) {
			$query = $this->db->executeQuery("select count(*) as num from hs_hr_emp_attendance where AddTime = {$AddTime}");
			$row = mysql_fetch_array($query, MYSQL_ASSOC);
			$num = intval($row['num']);
			$sql = "delete from hs_hr_emp_attendance where AddTime = {$AddTime}";
			$query = $this->db->executeQuery($sql);
			$records['test'] = "批量删除成功";
			$records['num'] = $num;
		} else {
			$records['test'] = "提交的时间有错误";
			$records['num'] = 0;
		}
	
		$path = "/templates/attendance/ExcelUpload.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}
	

	/**
	 *考勤原始记录 
	 **/
	public function ShowAttend_original() {
		$sysConst = new sysConf();
		$where = "Where 1=1 ";
		$where .= $this->GetSearchSlqWhere();
		$where_sp .= $this->GetSearchSlqWhere();


		
		$Year = intval($_REQUEST['Year']);
		$Month = intval($_REQUEST['Month']);
		if($Year > 0 && $Month > 0) {
			/*$Year = date("Y");
			$Month = intval(date("m"));*/
			$where .= " and a.Year={$Year} and a.Month ={$Month} ";
			$where_sp .= " and FROM_UNIXTIME(a.StartTime,'%Y%c')=".$Year.$Month;
		}



        $limit = "";
        $list = array();
		$pageNO = isset($_POST['pageNO'])?intval($_POST['pageNO']):1;
        if ($pageNO > 0) {
            $pageNO--;
            $pageNO *= $sysConst->itemsPerPage;

            $limit = " limit {$pageNO}, {$sysConst->itemsPerPage}";
        }
        
		$sql = "select count(*) as allcount from hs_hr_emp_attendance a left join hs_hr_employee b on b.emp_number = a.EmpId {$where}";
		$query = $this->db->executeQuery($sql);
		$Allcount = mysql_fetch_array($query, MYSQL_ASSOC);
		
		$sql = "select a.Id,a.RecordTime,b.employee_id,b.work_station,b.emp_lastname,b.emp_firstname,b.emp_middle_name,b.emp_nick_name from hs_hr_emp_attendance a left join hs_hr_employee b on b.emp_number = a.EmpId {$where} order by a.EmpId,a.RecordTime {$limit}";
		$query = $this->db->executeQuery($sql);
		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			$list[] = $row;
		}
		//把特别考勤的单记录考勤记录计入
		$list = $this->GetSpAdRecord($list,1,$where_sp);
		//print_r($list);
		//die();
		$records['list'] = $list;
		$records['pageNo'] = $pageNO;
		$records['Allcount'] = $Allcount['allcount'];
		$path = "/templates/attendance/ShowAttend_original.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}

	
	
	/**
	 *考勤有效记录 
	 **/
	public function ShowAttend_effectual($isGet="",$EmpId = "") {
		
		$sysConst = new sysConf();
		$where = "Where 1=1 ";
		$where .= $this->GetSearchSlqWhere();
        $limit = "";
        $list = array();
        $countlist = array();
        //$_POST['pageNO'] = 1;
		$pageNO = isset($_POST['pageNO'])?intval($_POST['pageNO']):1;
		//$page = $pageNO;
        if ($pageNO > 0) {
            $pageNO--;
            $pageNO *= $sysConst->itemsPerPage;

            $limit = " limit {$pageNO}, {$sysConst->itemsPerPage}";
        }
        
        //获取考勤规则
        if($this->RuleValue == "") {
        	$this->RuleValue = $this->getRuleValue();
        }
        
        //获取上下班时间
        $StartWorkTimeN = $this->RuleValue['xzDayStime'];
        $MiddleWorkTimeN = "12:00:00";
        $EndWorkTimeN = $this->RuleValue['xzDayEtime'];
        
		/*$sql = "select a.Id,b.emp_lastname,b.emp_firstname,b.emp_middle_name,b.emp_nick_name,MIN(a.RecordTime) as starttime,MAX(a.RecordTime) as endtime from hs_hr_emp_attendance a left join hs_hr_employee b on b.emp_number = a.EmpId {$where} group by CONCAT(a.Year,a.Month,a.Day),a.EmpId ";
		$query = $this->db->executeQuery($sql);
		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			$countlist[] = $row;
		}
		$Allcount = count($countlist);*/
		
		//获取考勤白名单
		if($this->newwiletlist == "") {
			$this->wilteList = $this->ShowAttend_whitelist(1);
			if(count($this->wilteList) > 0) {
				foreach ($this->wilteList as $key => $val) {
					$this->newwiletlist[$val['emp_number']][] = $val;
				}
			}
		}
		//获取周末和节假日
		if($this->WeekHolidays == "") {
			$AttendanceStatistics = new AttendanceStatistics();
			$this->WeekHolidays = $AttendanceStatistics->GetWeekAndHolidays();
		}
		
		$sql = "select a.Id,b.emp_number,b.emp_lastname,b.emp_firstname,b.emp_middle_name,b.emp_nick_name,MIN(a.RecordTime) as starttime,MAX(a.RecordTime) as endtime,a.Year,a.Month,a.Day from hs_hr_emp_attendance a left join hs_hr_employee b on b.emp_number = a.EmpId  {$where} group by CONCAT(a.Year,a.Month,a.Day),a.EmpId  order by starttime";
		$query = $this->db->executeQuery($sql);
		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			$row['beizhu'] = "";
			$IsWhite = false;
			$IsWeek = false;
			$IsHoliday = false;
			//判断迟到
			$StartWorkTime = strtotime("{$row['Year']}-{$row['Month']}-{$row['Day']} {$StartWorkTimeN}");
			$EndWorkTime = strtotime("{$row['Year']}-{$row['Month']}-{$row['Day']} {$EndWorkTimeN}");
			$MiddleWorkTime = strtotime("{$row['Year']}-{$row['Month']}-{$row['Day']} {$MiddleWorkTimeN}");
			//排除节假日
			$HolidayResult = $this->RemoveHoliday($row,$StartWorkTime,$MiddleWorkTime);
			$row = $HolidayResult['row'];
			$IsHoliday = $HolidayResult['IsHoliday'];
			if($IsHoliday == false) {
				//排除周末
				$WeekResult = $this->RemoveWeek($row,$StartWorkTime,$MiddleWorkTime);
				$row = $WeekResult['row'];
				$IsWeek = $WeekResult['IsWeek'];
				if($IsWeek == false) {
					//排除考勤白名单
					$WhileListResult = $this->RemoveWhitelist($row['emp_number'],$row,$StartWorkTime,$EndWorkTime);
					$row = $WhileListResult['row'];
					$IsWhite = $WhileListResult['IsWhite'];
				}
			}
			if($IsWhite || $IsWeek || $IsHoliday) {
				//比较打卡时间和规定时间得出最早时间
				if($StartWorkTime < $row['starttime']) {
					$row['starttime'] = $StartWorkTime;
				}
				//比较打卡时间和规定时间得出最晚时间
				if($EndWorkTime > $row['endtime']) {
					$row['endtime'] = $EndWorkTime;
				}
				if($IsHoliday) $row['beizhu'] = "节假日";
				elseif($IsWeek) $row['beizhu'] = "周末";
				else $row['beizhu'] = "白名单";
			} elseif($row['NoJisuan'] != 1) {
				$row = $this->GetZaoTuiKuang($row,$StartWorkTime,$EndWorkTime,$this->RuleValue);
			}
			$row['riqi'] = @date('Y-m-d',$row['starttime']);
			$list[@date('Y-m-d',$row['starttime'])."-".$row['emp_number']] = $row;
		}

		
		//查出所有的员工以及入职日期
		$sql = "select joined_date,emp_number,emp_firstname,emp_lastname from hs_hr_employee";
		$query = $this->db->executeQuery($sql);
		while ($date = mysql_fetch_array($query, MYSQL_ASSOC)) {
			if($date['joined_date'] == "") continue;
			//$row['dayCount'] = floor((time() - strtotime($row['joined_date'])) / (3600*24));
			$nowtime = time();
			for ($j = strtotime($date['joined_date']); $j <$nowtime;$j += 3600*24) {
				if(!isset($list[@date('Y-m-d',$j)."-".$date['emp_number']])) {
					$ThatDay = @date("Y-m-d",$j);
					$StartWorkTime = strtotime("{$ThatDay} {$StartWorkTimeN}");
					$EndWorkTime = strtotime("{$ThatDay} {$EndWorkTimeN}");
					
					//排除节假日
					$HolidayResult = $this->RemoveHoliday($date,$StartWorkTime,$MiddleWorkTime);
					$date = $HolidayResult['row'];
					$IsHoliday = $HolidayResult['IsHoliday'];
					if($IsHoliday == false) {
						//排除周末
						$WeekResult = $this->RemoveWeek($date,$StartWorkTime,$MiddleWorkTime);
						$date = $WeekResult['row'];
						$IsWeek = $WeekResult['IsWeek'];
						if($IsWeek == false) {
							//排除考勤白名单
							$WhileListResult = $this->RemoveWhitelist($date['emp_number'],$date,$StartWorkTime,$EndWorkTime);
							$IsWhite = $WhileListResult['IsWhite'];
							$date = $WhileListResult['row'];
						}
					}
					if($IsWhite || $IsWeek || $IsHoliday) {
						//比较打卡时间和规定时间得出最早时间
						$date['starttime'] = "";
						$date['endtime'] = "";
						if($IsHoliday) $date['beizhu'] = "节假日";
						elseif($IsWeek) $date['beizhu'] = "周末";
						else $date['beizhu'] = "白名单";
					} elseif($date['NoJisuan'] != 1) {
						$date = $this->GetZaoTuiKuang($date,$StartWorkTime,$EndWorkTime,$this->RuleValue);
					}
					$date['riqi'] = @date('Y-m-d',$j);
					$list[@date('Y-m-d',$j)."-".$date['emp_number']] = $date;
					//$list[date('Y-m-d',$j)."-".$date['emp_number']] = array('beizhu'=>"旷工",'LkuangGong'=>1,'riqi'=>date('Y-m-d',$j),'emp_firstname'=>$date['emp_firstname'],'emp_lastname'=>$date['emp_lastname']);
				}
			}
		}
		if($isGet == 1) return $list;
		$i = 0;
		$j = 0;
		//sort($list);
		$count = count($list);
		if($count > 0) {
			foreach ($list as $key => $val) {
				$i++;
				if($i <= $pageNO) continue;
				if($i > ($pageNO+$sysConst->itemsPerPage)) break;
				$newlist[$key] = $val;
				
				
			}
		}
		$records['list'] = $newlist;
		$records['pageNo'] = $pageNO;
		$records['Allcount'] = $count;
		//echo "<pre>";
		//print_r($newlist);
		//die();
		$path = "/templates/attendance/ShowAttend_effectual.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}
	
	
	
	/**
	 *考勤汇总班制的考勤有效记录 
	 **/
	public function ShowAttend_effectual_LunBan($isGet="",$EmpId = "") {
		
		$sysConst = new sysConf();
		//$where = " Where a.Classes in (3,4,5) ";
		$where = " Where 1=1 ";
		$where2 = " Where 1=1 ";
		$where .= $this->GetSearchSlqWhere();
		$where2 .= $this->GetSearchSlqWhere();
		if($EmpId != "") {
			$where .= " and b.emp_number = {$EmpId} ";
			$where2 .= " and b.emp_number = {$EmpId} ";
		}
		$Year = intval($_REQUEST['Year']);
		$Month = intval($_REQUEST['Month']);
		if($Year > 0 && $Month > 0) {
			/*$Year = date("Y");
			$Month = intval(date("m"));*/
			$where .= " and a.Year={$Year} and a.Month ={$Month} ";
			$where2 .= " and a.m_year={$Year} and a.m_month ={$Month} ";
			$MonthStartTime = mktime(0, 0, 0, $Month, 1, $Year);
			$MonthEndTime = mktime(0, 0, 0, $Month+1, 1, $Year);
		}
		
        $limit = "";
        $list = array();
        $countlist = array();
        //$_POST['pageNO'] = 1;
		$pageNO = isset($_POST['pageNO'])?intval($_POST['pageNO']):1;
		//$page = $pageNO;
        if ($pageNO > 0 && $isGet != 1) {
            $pageNO--;
            $pageNO *= $sysConst->itemsPerPage;

            $limit = " limit {$pageNO}, {$sysConst->itemsPerPage}";
        }
        
        //获取考勤规则
        if($this->RuleValue == "") {
        	$this->RuleValue = $this->getRuleValue();
        }
        
        //获取3班倒考勤规则
        if($this->LunRuleValue == "") {
        	$this->LunRuleValue = $this->getRuleValue('ClassRule');
        }

		//查出所有3班制的人的打开记录
		$AllAdArr = array();
		$sql = "select a.Id,a.Classes,b.employee_id,b.work_station,b.emp_number,b.emp_lastname,b.emp_firstname,b.emp_middle_name,b.emp_nick_name,a.RecordTime,a.Year,a.Month,a.Day from hs_hr_emp_attendance a left join hs_hr_employee b on b.emp_number = a.EmpId  {$where}  order by RecordTime";

		$query = $this->db->executeQuery($sql);
		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			$AllAdArr[$row['emp_number']][$row['Year']."-".$row['Month']."-".$row['Day']][$row['RecordTime']] = $row;
		}
		
		//把特别考勤的单记录考勤记录计入
		$AllAdArr = $this->GetSpAdRecord($AllAdArr);
		//获取所有人的加班
		$AllWorkOut = $this->GetOutWordTIme($MonthStartTime,$MonthEndTime);
		//查询出所有员工的排班表
		$AllBanZhiLunArr = array();
		
		$sql = "select count(*) as allcount from hs_hr_argclass_members a left join hs_hr_employee b on b.emp_number = a.mbid  {$where2} order by id";
		$query = $this->db->executeQuery($sql);
		$Allcount = mysql_fetch_array($query, MYSQL_ASSOC);
	
		$sql = "select a.id,a.m_year,a.m_month,a.mbid,a.m_class,b.employee_id,b.work_station,b.emp_number,b.emp_lastname,b.emp_firstname,b.emp_middle_name,b.emp_nick_name from hs_hr_argclass_members a left join hs_hr_employee b on b.emp_number = a.mbid  {$where2} order by id {$limit}";
		//echo $sql;die();
		//echo $sql."<br>";
		$query = $this->db->executeQuery($sql);
		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			if(intval($row['emp_number']) <= 0) continue;
			$monthdate = unserialize($row['m_class']);
			//循环得到这个月的上班时间
			foreach ($monthdate as $key => $val) {
				$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['SWtime'] = $this->LunRuleValue['starttime'.$val];
				if(in_array($val,$this->AttendanceCache['TowRest'])) {
					$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['EZWtime'] = $this->LunRuleValue['resttime_start'.$val.'1'];
					$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['SZWtime'] = $this->LunRuleValue['resttime_end'.$val.'1'];
					$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['EZ2Wtime'] = $this->LunRuleValue['resttime_start'.$val.'2'];
					$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['SZ2Wtime'] = $this->LunRuleValue['resttime_end'.$val.'2'];
				} else {
					$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['EZWtime'] = $this->LunRuleValue['resttime_start'.$val];
					$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['SZWtime'] = $this->LunRuleValue['resttime_end'.$val];
				}
				$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['EWtime'] = $this->LunRuleValue['endtime'.$val];
				$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['resttime_need'] = $this->LunRuleValue['resttime_need'.$val]; //是否需要打卡
				$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['m_year'] = $row['m_year'];
				$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['m_month'] = $row['m_month'];
				$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['Hours'] = $this->LunRuleValue['hours'.$val];
				$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['m_day'] = $key;
				$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['dtime'] = strtotime($row['m_year']."-".$row['m_month']."-".$key);
				$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['banbie'] = $val;
				$AllBanZhiLunArr[$row['mbid']][$row['m_year']."-".$row['m_month']."-".$key]['info'] = $row;
			}
		}
		
		/* echo "<pre>";
		echo count($AllBanZhiLunArr);
		print_r($AllBanZhiLunArr);
		die(); */
		
		if(count($AllBanZhiLunArr) > 0) {
			foreach ($AllBanZhiLunArr as $emp => $Ymd) {
				foreach ($Ymd as $dkey => $dval) {
					//获取该日的打开时间,有打卡记录的读取
					$row = "";
					if($AllAdArr[$emp][$dkey]) {
						$allRecord = $AllAdArr[$emp][$dkey];
						$keyArr = array_keys($allRecord);
						$Maxkey = max($keyArr);
						$row = $allRecord[$Maxkey];
					} else {
						$row = $dval['info'];
					}
					$row['yeban'] = 0;
					if(isset($this->AttendanceCache['LunBanType'][$dval['banbie']])) {
						if(in_array($dval['banbie'],$this->AttendanceCache['DayBan'])) {
							//判断迟到
							$StartWorkTime = strtotime(@date("Y-m-d",$dval['dtime'])." {$dval['SWtime']}");
							$EndWorkTime = strtotime(@date("Y-m-d",$dval['dtime'])." {$dval['EWtime']}");
							$canAtime = $StartWorkTime - $this->RuleValue['BeforeWorkLong']*60;
							$canFtime = $EndWorkTime + $this->RuleValue['AfterWorkLong']*60;
							$MiddleEndWorkTime = strtotime(@date("Y-m-d",$dval['dtime'])." {$dval['EZWtime']}");
							$MiddleStartWorkTime = strtotime(@date("Y-m-d",$dval['dtime'])." {$dval['SZWtime']}");
							$row['MiddleRecordOk'] = 1;
							//判断中间是否打卡
							if($dval['resttime_need']  == 1)  {
								foreach ($allRecord as $key2 => $val2) {
									if($key2 >= $MiddleEndWorkTime && $key2 <= ($MiddleEndWorkTime + $this->RuleValue['AfMiddleLong']*60)) {
										$row['MiddleAftime'] = $val2['RecordTime'];
										break;
									}
								}
								
								foreach ($allRecord as $key2 => $val2) {
									if($key2 <= $MiddleStartWorkTime && $key2 >= ($MiddleStartWorkTime - $this->RuleValue['StMiddleLong']*60)) {
										$row['MiddleSttime'] = $val2['RecordTime'];
										break;
									}
								}
								
								if($row['MiddleAftime']  == "" || $row['MiddleSttime'] == "")  {
									$row['MiddleRecordOk'] = 0;
								}
								
								if ($dval['EZ2Wtime'] != "" && $dval['EZ2Wtime'] != "") {
									$Middle2EndWorkTime = strtotime(@date("Y-m-d",$dval['dtime'])." {$dval['EZ2Wtime']}");
									$Middle2StartWorkTime = strtotime(@date("Y-m-d",$dval['dtime'])." {$dval['SZ2Wtime']}");
									//判断中间是否打卡
									foreach ($allRecord as $key2 => $val2) {
										if($key2 >= $Middle2EndWorkTime && $key2 <= ($Middle2EndWorkTime + $this->RuleValue['AfMiddleLong']*60)) {
											$row['Middle2Aftime'] = $val2['RecordTime'];
											break;
										}
									}
									
									foreach ($allRecord as $key2 => $val2) {
										if($key2 <= $Middle2StartWorkTime && $key2 >= ($Middle2StartWorkTime - $this->RuleValue['StMiddleLong']*60)) {
											$row['Middle2Sttime'] = $val2['RecordTime'];
											break;
										}
									}
									
									if($row['Middle2Aftime']  == "" || $row['Middle2Sttime'] == "")  {
										$row['MiddleRecordOk'] = 0;
									}
									
								}
							}
							ksort($allRecord);//小的排在前面
							foreach ($allRecord as $key2 => $val2) {
								if($key2 >= $canAtime && $key2 < $EndWorkTime) {
									$row['starttime'] = $val2['RecordTime'];
									break;
								}
							}
							krsort($allRecord);//大的排在前面
							foreach ($allRecord as $key2 => $val2) {
								if($key2 <= $canFtime && $key2 > $StartWorkTime) {
									$row['endtime'] = $val2['RecordTime'];
									break;
								}
							}
						}  elseif(in_array($dval['banbie'],$this->AttendanceCache['NightBan']))  {
							//判断迟到
							$StartWorkTime = strtotime(@date("Y-m-d",$dval['dtime'])." {$dval['SWtime']}");
							$EndWorkTime = strtotime(@date("Y-m-d",$StartWorkTime+3600*24)." {$dval['EWtime']}");
							$MiddleWorkTime = strtotime(@date("Y-m-d",$StartWorkTime+3600*24)." {$dval['EZWtime']}");
							$MiddleEndWorkTime = strtotime(@date("Y-m-d",$EndWorkTime)." {$dval['EZWtime']}");
							$MiddleStartWorkTime = strtotime(@date("Y-m-d",$EndWorkTime)." {$dval['SZWtime']}");
							$canAtime = $StartWorkTime - $this->RuleValue['BeforeWorkLong']*60;
							$canFtime = $EndWorkTime + $this->RuleValue['AfterWorkLong']*60;
							$row['yeban'] =1;
							if(@date("G",$dval['dtime']." {$dval['EZWtime']}") > @date("G",$StartWorkTime)) {
								$MiddleEndWorkTime = strtotime(@date("Y-m-d",$StartWorkTime)." {$dval['EZWtime']}");
							} else {
								$MiddleEndWorkTime = strtotime(@date("Y-m-d",$EndWorkTime)." {$dval['EZWtime']}");
							}
							if(@date("G",$dval['dtime']." {$dval['SZWtime']}") < date("G",$EndWorkTime)) {
								$MiddleStartWorkTime = strtotime(@date("Y-m-d",$EndWorkTime)." {$dval['SZWtime']}");
							} else {
								$MiddleStartWorkTime = strtotime(@date("Y-m-d",$StartWorkTime)." {$dval['SZWtime']}");
							}
							$row['MiddleRecordOk'] = 1;
							//判断中间是否打卡
							if($dval['resttime_need']  == 1)  {
								if(isset($AllAdArr[$emp][@date("Y-n-j",$EndWorkTime)])) {
									krsort($AllAdArr[$emp][@date("Y-n-j",$EndWorkTime)]);//大的排在前面
									$toallRecord = $AllAdArr[$emp][@date("Y-n-j",$EndWorkTime)];
								}
									foreach ($toallRecord as $key2 => $val2) {
										if($key2 >= $MiddleEndWorkTime && $key2 <= ($MiddleEndWorkTime + $this->RuleValue['AfMiddleLong']*60)) {
											$row['MiddleAftime'] = $val2['RecordTime'];
											break;
										}
									}
									
									foreach ($toallRecord as $key2 => $val2) {
										if($key2 <= $MiddleStartWorkTime && $key2 >= ($MiddleStartWorkTime - $this->RuleValue['StMiddleLong']*60)) {
											$row['MiddleSttime'] = $val2['RecordTime'];
											break;
										}
									}
									
									if($row['MiddleAftime']  == "" || $row['MiddleSttime'] == "")  {
										$row['MiddleRecordOk'] = 0;
									}
									
									if ($dval['EZ2Wtime'] != "" && $dval['EZ2Wtime'] != "") {
										if(@date("G",$dval['dtime']." {$dval['EZ2Wtime']}") > @date("G",$StartWorkTime)) {
											$Middle2EndWorkTime = strtotime(@date("Y-m-d",$StartWorkTime)." {$dval['EZ2Wtime']}");
										} else {
											$Middle2EndWorkTime = strtotime(@date("Y-m-d",$EndWorkTime)." {$dval['EZ2Wtime']}");
										}
										if(@date("G",$dval['dtime']." {$dval['SZ2Wtime']}") < @date("G",$EndWorkTime)) {
											$Middle2StartWorkTime = strtotime(@date("Y-m-d",$EndWorkTime)." {$dval['SZ2Wtime']}");
										} else {
											$Middle2StartWorkTime = strtotime(@date("Y-m-d",$StartWorkTime)." {$dval['SZ2Wtime']}");
										}
										
										//判断中间是否打卡
										foreach ($toallRecord as $key2 => $val2) {
											if($key2 >= $Middle2EndWorkTime && $key2 <= ($Middle2EndWorkTime + $this->RuleValue['AfMiddleLong']*60)) {
												$row['Middle2Aftime'] = $val2['RecordTime'];
												break;
											}
										}
										
										foreach ($toallRecord as $key2 => $val2) {
											if($key2 <= $Middle2StartWorkTime && $key2 >= ($Middle2StartWorkTime - $this->RuleValue['StMiddleLong']*60)) {
												$row['Middle2Sttime'] = $val2['RecordTime'];
												break;
											}
										}
										
										if($row['Middle2Aftime']  == "" || $row['Middle2Sttime'] == "")  {
											$row['MiddleRecordOk'] = 0;
										}
									}
							}
							ksort($allRecord);//小的排在前面
							foreach ($allRecord as $key2 => $val2) {
								if($key2 >= $canAtime) {
									$row['starttime'] = $val2['RecordTime'];
									break;
								}
							}
							
							if(isset($AllAdArr[$emp][@date("Y-n-j",$row['starttime']+3600*24)])) {
								krsort($AllAdArr[$emp][@date("Y-n-j",$row['starttime']+3600*24)]);//大的排在前面
								foreach ($AllAdArr[$emp][@date("Y-n-j",$row['starttime']+3600*24)] as $key2 => $val2) {
									if($key2 <= $canFtime) {
										$row['endtime'] = $val2['RecordTime'];
										break;
									}
								}
							} else {
								$row['endtime'] = "";
							}
						} 
						//获得一天的加班
						$row['pcOTtime'] = intval($AllWorkOut[$emp][@date("Ynj",$dval['dtime'])][9]['time']);
						$row['WeekOTtime'] = intval($AllWorkOut[$emp][@date("Ynj",$dval['dtime'])][10]['time']);
						$row['HolidayOTtime'] = intval($AllWorkOut[$emp][@date("Ynj",$dval['dtime'])][11]['time']);
						
						$row['beizhu'] = "";
						$IsWhite = false;
						$IsSpAd = false;
						
						//排除考勤白名单
						$WhileListResult = $this->RemoveWhitelist($row['emp_number'],$row,$StartWorkTime,$EndWorkTime);
						$row = $WhileListResult['row'];
						$IsWhite = $WhileListResult['IsWhite'];
						if($IsWhite == false) {
							$SpAdResult = $this->RemoveSpAd($row,$StartWorkTime,$EndWorkTime);
							$row = $SpAdResult['row'];
							$IsSpAd = $SpAdResult['IsSpAd'];
						}
								
						if($IsWhite || $IsSpAd) {
							//比较打卡时间和规定时间得出最早时间
							if($StartWorkTime < $row['starttime']) {
								$row['starttime'] = $StartWorkTime;
							}
							//比较打卡时间和规定时间得出最晚时间
							if($EndWorkTime > $row['endtime']) {
								$row['endtime'] = $EndWorkTime;
							}
							if($IsWhite) $row['beizhu'] = "白名单";
							else $row['beizhu'] = $this->AttendanceCache['SpecialAdType'][$row['info']['TypeId']];
						} elseif($row['NoJisuan'] != 1) {
							$row = $this->GetZaoTuiKuang($row,$StartWorkTime,$EndWorkTime,$this->RuleValue);
						}
						
						if ($row['LkuangGong'] != 1 && $row['ZkuangGong'] != 1 && $row['MiddleRecordOk'] == 1) {
							$row['WorkHours'] = round($dval['Hours'],1) - $row['laterHours'];
						}
						$row['Hours'] = $dval['Hours'];
						
					} else {
						$row['beizhu'] = $this->AttendanceCache['LunBanType'][$dval['banbie']];
					}
					$row['workOutInfo'] = array();
					//循环每一次加班获取加班应该打卡的时间
					foreach($AllWorkOut[$emp][@date("Ynj",$dval['dtime'])]['getworktime'] as $key => $val) {
						$canAtimeOT = $val['StartTime'] - $this->RuleValue['BeforeWorkLong']*60;
						$canFtimeOT = $val['EndTime'] + $this->RuleValue['AfterWorkLong']*60;
						ksort($allRecord);//小的排在前面
						foreach ($allRecord as $key2 => $val2) {
							if($key2 >= $canAtimeOT && $key2 <= $val['StartTime']) {
								$val['StartTimeOT'] = $val2['RecordTime'];
								break;
							}
						}
						//判断加班不夸日
						if(date("Y-m-d",$val['StartTime']) == date("Y-m-d",$val['EndTime'])) {
							krsort($allRecord);//大的排在前面
							foreach ($allRecord as $key2 => $val2) {
								if($key2 <= $canFtimeOT && $key2 >= $val['EndTime']) {
									$val['EndTimeOT'] = $val2['RecordTime'];
									break;
								}
							}
						} else {
							//加班跨日
							krsort($AllAdArr[$emp][@date("Y-n-j",$val['starttime']+3600*24)]);//大的排在前面
							foreach ($AllAdArr[$emp][@date("Y-n-j",$val['starttime']+3600*24)] as $key2 => $val2) {
								if($key2 <= $canFtimeOT  && $key2 >= $val['EndTime']) {
									$row['EndTimeOT'] = $val2['RecordTime'];
									break;
								}
							}
							
						}
						
						$row['workOutInfo'][] = $val;
					}
						
					
					
					$row['riqi'] = @date('Y-m-d',$dval['dtime']);
					$dval['other'] = $row;
					$list[@date('Y-m-d',$dval['dtime'])."-".$emp] = $dval;
			}
			}
		}
		
		/*echo "<pre>";
		print_r($list);
		die();*/

		if($isGet == 1) return $list;
		$i = 0;
		$j = 0;
		//sort($list);
		$count = $Allcount['allcount'];//count($list);
		/*if($count > 0) {
			foreach ($list as $key => $val) {
				$i++;
				if($i <= $pageNO) continue;
				if($i > ($pageNO+$sysConst->itemsPerPage)) break;
				$newlist[$key] = $val;
			}
		}*/
		$records['list'] = $list;//$newlist;
		$records['pageNo'] = $pageNO;
		$records['Allcount'] = $count;
		//echo "<pre>";
		//print_r($newlist);
		//die();
		$path = "/templates/attendance/ShowAttend_effectual_lun.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}
	
	
	
	/**
	 *新的考勤有效记录包括夜班 
	 **/
	public function ShowAttend_effectual_new($isGet="",$EmpId = "",$isChun="") {
		
		$sysConst = new sysConf();
		$where = "Where a.Classes in (1,2) ";
		$where2 = " Where 1=1 ";
		$where .= $this->GetSearchSlqWhere();
		$where2 .= $this->GetSearchSlqWhere();

		if($EmpId != "") {
			$where .= " and a.EmpId = {$EmpId} ";
			$where2 .= " and emp_number = {$EmpId} ";
		}
        $limit = "";
        $list = array();
        $countlist = array();
        //$_POST['pageNO'] = 1;
		$pageNO = isset($_POST['pageNO'])?intval($_POST['pageNO']):1;
		//$page = $pageNO;
        if ($pageNO > 0) {
            $pageNO--;
            $pageNO *= $sysConst->itemsPerPage;

            $limit = " limit {$pageNO}, {$sysConst->itemsPerPage}";
        }
        
        //获取考勤规则
        if($this->RuleValue == "") {
        	$this->RuleValue = $this->getRuleValue();
        }
        
        //获取上下班时间
        /*$StartWorkTimeN = $this->RuleValue['xzDayStime'];
        $MiddleWorkTimeN = $this->RuleValue['xzDayMEtime'];
        $EndWorkTimeN = $this->RuleValue['xzDayEtime'];*/
 
		
		//获取考勤白名单
		if($this->newwiletlist == "") {
			$this->wilteList = $this->ShowAttend_whitelist(1);
			if(count($this->wilteList) > 0) {
				foreach ($this->wilteList as $key => $val) {
					$this->newwiletlist[$val['emp_number']][] = $val;
				}
			}
		}
		//获取周末和节假日
		if($this->WeekHolidays == "") {
			$AttendanceStatistics = new AttendanceStatistics();
			$this->WeekHolidays = $AttendanceStatistics->GetWeekAndHolidays();
		}
		
		$AllAdArr = array();
		$sql = "select a.Id,a.Classes,b.employee_id,b.work_station,b.emp_number,b.emp_lastname,b.emp_firstname,b.emp_middle_name,b.emp_nick_name,a.RecordTime,a.Year,a.Month,a.Day from hs_hr_emp_attendance a left join hs_hr_employee b on b.emp_number = a.EmpId  {$where}  order by RecordTime";
		$query = $this->db->executeQuery($sql);
		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			$AllAdArr[$row['emp_number']][$row['Year'].$row['Month'].$row['Day']][$row['RecordTime']] = $row;
		}
		//把特别考勤的单记录考勤记录计入
		$AllAdArr = $this->GetSpAdRecord($AllAdArr);
		//获取所有人的加班
		$AllWorkOut = $this->GetOutWordTIme();
		if(count($AllAdArr) > 0) {
			foreach ($AllAdArr as $emp => $Ymd) {
				foreach ($Ymd as $key => $val) {
					$keyArr = array_keys($val);
					$Maxkey = max($keyArr);
					$row = $val[$Maxkey];
					if($row['Classes'] == 1) {
						//判断迟到
						$StartWorkTime = strtotime(@date("Y-m-d",$row['RecordTime'])." {$this->RuleValue['xzDayStime']}");
						$EndWorkTime = strtotime(@date("Y-m-d",$row['RecordTime'])." {$this->RuleValue['xzDayEtime']}");
						$MiddleWorkTime = $MiddleEndWorkTime = strtotime(@date("Y-m-d",$row['RecordTime'])." {$this->RuleValue['xzDayMEtime']}");
						$MiddleStartWorkTime = strtotime(@date("Y-m-d",$row['RecordTime'])." {$this->RuleValue['xzDayMStime']}");
						$canAtime = $StartWorkTime - $this->RuleValue['BeforeWorkLong']*60;
						$canFtime = $EndWorkTime + $this->RuleValue['AfterWorkLong']*60;
						//判断中间是否打卡
						foreach ($val as $key2 => $val2) {
							if($key2 >= $MiddleEndWorkTime && $key2 <= ($MiddleEndWorkTime + $this->RuleValue['AfMiddleLong']*60)) {
								$row['MiddleAftime'] = $val2['RecordTime'];
								break;
							}
						}
						
						foreach ($val as $key2 => $val2) {
							if($key2 <= $MiddleStartWorkTime && $key2 >= ($MiddleStartWorkTime - $this->RuleValue['StMiddleLong']*60)) {
								$row['MiddleSttime'] = $val2['RecordTime'];
								break;
							}
						}
						
						//吧不符合的考勤记录取消
						ksort($val);//小的排在前面
						foreach ($val as $key2 => $val2) {
							if($key2 >= $canAtime && $key2 < $EndWorkTime) {
								$row['starttime'] = $val2['RecordTime'];
								break;
							}
						}
						krsort($val);//大的排在前面
						foreach ($val as $key2 => $val2) {
							if($key2 <= $canFtime && $key2 > $StartWorkTime) {
								$row['endtime'] = $val2['RecordTime'];
								break;
							}
						}
						/*$row['endtime'] = $val[$Maxkey]['RecordTime'];
						$Minkey = min($keyArr);
						$row['starttime'] = $val[$Minkey]['RecordTime'];*/
					} else {
						//判断迟到
						$StartWorkTime = strtotime(@date("Y-m-d",$row['RecordTime'])." {$this->RuleValue['xzNightStime']}");
						$canAtime = $StartWorkTime - $this->RuleValue['BeforeWorkLong']*60;
						$EndWorkTime = strtotime(@date("Y-m-d",$StartWorkTime+3600*24)." {$this->RuleValue['xzNightEtime']}");
						$canFtime = $EndWorkTime + $this->RuleValue['AfterWorkLong']*60;
						$MiddleWorkTime = strtotime(@date("Y-m-d",$StartWorkTime+3600*24)." {$this->RuleValue['xzNightMEtime']}");
						if(@date("G",$row['RecordTime']." {$this->RuleValue['xzNightMEtime']}") > @date("G",$StartWorkTime)) {
							$MiddleEndWorkTime = strtotime(@date("Y-m-d",$StartWorkTime)." {$this->RuleValue['xzNightMEtime']}");
						} else {
							$MiddleEndWorkTime = strtotime(@date("Y-m-d",$EndWorkTime)." {$this->RuleValue['xzNightMEtime']}");
						}
						if(@date("G",$row['RecordTime']." {$this->RuleValue['xzNightMStime']}") < @date("G",$EndWorkTime)) {
							$MiddleStartWorkTime = strtotime(@date("Y-m-d",$EndWorkTime)." {$this->RuleValue['xzNightMStime']}");
						} else {
							$MiddleStartWorkTime = strtotime(@date("Y-m-d",$StartWorkTime)." {$this->RuleValue['xzNightMStime']}");
						}
						
						//判断中间是否打卡
						foreach ($val as $key2 => $val2) {
							if($key2 >= $MiddleEndWorkTime && $key2 <= ($MiddleEndWorkTime + $this->RuleValue['AfMiddleLong']*60)) {
								$row['MiddleAftime'] = $val2['RecordTime'];
								break;
							}
						}
						
						foreach ($val as $key2 => $val2) {
							if($key2 <= $MiddleStartWorkTime && $key2 >= ($MiddleStartWorkTime - $this->RuleValue['StMiddleLong']*60)) {
								$row['MiddleSttime'] = $val2['RecordTime'];
								break;
							}
						}
						
						ksort($val);//小的排在前面
						foreach ($val as $key2 => $val2) {
							if($key2 >= $canAtime) {
								$row['starttime'] = $val2['RecordTime'];
								break;
							}
						}
						
						if(isset($Ymd[@date("Ynj",$row['starttime']+3600*24)])) {
							krsort($Ymd[@date("Ynj",$row['starttime']+3600*24)]);//大的排在前面
							foreach ($Ymd[@date("Ynj",$row['starttime']+3600*24)] as $key2 => $val2) {
								if($key2 <= $canFtime) {
									$row['endtime'] = $val2['RecordTime'];
									break;
								}
							}
						} else {
							$row['endtime'] = "";
						}
					}
					//获得一天的加班
					$row['pcOTtime'] = intval($AllWorkOut[$emp][@date("Ynj",$row['starttime'])][9]['time']);
					$row['WeekOTtime'] = intval($AllWorkOut[$emp][@date("Ynj",$row['starttime'])][10]['time']);
					$row['HolidayOTtime'] = intval($AllWorkOut[$emp][@date("Ynj",$row['starttime'])][11]['time']);

					$row['beizhu'] = "";
					$IsWhite = false;
					$IsWeek = false;
					$IsHoliday = false;
					$IsSpAd = false;
					//统计加班
					//排除节假日
						$HolidayResult = $this->RemoveHoliday($row,$StartWorkTime,$MiddleWorkTime);
						$row = $HolidayResult['row'];
						$IsHoliday = $HolidayResult['IsHoliday'];
						if($IsHoliday == false) {
							//排除周末
							$WeekResult = $this->RemoveWeek($row,$StartWorkTime,$MiddleWorkTime);
							$row = $WeekResult['row'];
							$IsWeek = $WeekResult['IsWeek'];
							if($IsWeek == false) {
								//排除考勤白名单
								$WhileListResult = $this->RemoveWhitelist($row['emp_number'],$row,$StartWorkTime,$EndWorkTime);
								$row = $WhileListResult['row'];
								$IsWhite = $WhileListResult['IsWhite'];
								if($IsWhite == false) {
									$SpAdResult = $this->RemoveSpAd($row,$StartWorkTime,$EndWorkTime);
									$row = $SpAdResult['row'];
									$IsSpAd = $SpAdResult['IsSpAd'];
								}
							}
						}
					
					if($IsWhite || $IsWeek || $IsHoliday || $IsSpAd) {
						//比较打卡时间和规定时间得出最早时间
						if($StartWorkTime < $row['starttime']) {
							$row['starttime'] = $StartWorkTime;
						}
						//比较打卡时间和规定时间得出最晚时间
						if($EndWorkTime > $row['endtime']) {
							$row['endtime'] = $EndWorkTime;
						}
						if($IsHoliday) $row['beizhu'] = "节假日";
						elseif($IsWeek) $row['beizhu'] = "周末";
						elseif($IsWhite) $row['beizhu'] = "白名单";
						else $row['beizhu'] = $this->AttendanceCache['SpecialAdType'][$row['info']['TypeId']];
					} elseif($row['NoJisuan'] != 1) {
						$row = $this->GetZaoTuiKuang($row,$StartWorkTime,$EndWorkTime,$this->RuleValue);
					}
					$row['riqi'] = @date('Y-m-d',$row['RecordTime']);
					$list[@date('Y-m-d',$row['RecordTime'])."-".$row['emp_number']] = $row;
				}
			}
		}

		/*echo "<pre>";
		print_r($list);
		die();*/
		//查出所有的员工以及入职日期
		$sql = "select joined_date,employee_id,work_station,emp_number,emp_firstname,emp_lastname from hs_hr_employee {$where2}";
		$query = $this->db->executeQuery($sql);
		while ($date = mysql_fetch_array($query, MYSQL_ASSOC)) {
			if($date['joined_date'] == "") continue;
			//$row['dayCount'] = floor((time() - strtotime($row['joined_date'])) / (3600*24));
			$nowtime = time();
			for ($j = strtotime($date['joined_date']); $j <$nowtime;$j += 3600*24) {
				if(!isset($list[@date('Y-m-d',$j)."-".$date['emp_number']])) {
					$ThatDay = @date("Y-m-d",$j);
					$StartWorkTime = strtotime("{$ThatDay} {$this->RuleValue['xzDayStime']}");
					$EndWorkTime = strtotime("{$ThatDay} {$this->RuleValue['xzDayEtime']}");
					$DayDate = $date;
					$IsWhite = false;
					$IsWeek = false;
					$IsHoliday = false;
					$IsSpAd = false;
					//排除节假日
						$HolidayResult = $this->RemoveHoliday($DayDate,$StartWorkTime,$MiddleWorkTime);
						$DayDate = $HolidayResult['row'];
						$IsHoliday = $HolidayResult['IsHoliday'];
						if($IsHoliday == false) {
							//排除周末
							$WeekResult = $this->RemoveWeek($DayDate,$StartWorkTime,$MiddleWorkTime);
							$DayDate = $WeekResult['row'];
							$IsWeek = $WeekResult['IsWeek'];
							if($IsWeek == false) {
								//排除考勤白名单
								$WhileListResult = $this->RemoveWhitelist($DayDate['emp_number'],$DayDate,$StartWorkTime,$EndWorkTime);
								$IsWhite = $WhileListResult['IsWhite'];
								$DayDate = $WhileListResult['row'];
								if($IsWhite == false) {
									$SpAdResult = $this->RemoveSpAd($DayDate,$StartWorkTime,$EndWorkTime);
									$IsSpAd = $SpAdResult['IsSpAd'];
									$DayDate = $SpAdResult['row'];
								}
							}
						}
					if($IsWhite || $IsWeek || $IsHoliday || $IsSpAd) {
						//比较打卡时间和规定时间得出最早时间
						$DayDate['starttime'] = "";
						$DayDate['endtime'] = "";
						if($IsHoliday) $DayDate['beizhu'] = "节假日";
						elseif($IsWeek) $DayDate['beizhu'] = "周末";
						elseif($IsWhite) $DayDate['beizhu'] = "白名单";
						else $DayDate['beizhu'] = $this->AttendanceCache['SpecialAdType'][$DayDate['info']['TypeId']];
					} elseif($DayDate['NoJisuan'] != 1) {
						$DayDate = $this->GetZaoTuiKuang($DayDate,$StartWorkTime,$EndWorkTime,$this->RuleValue);
					}
					//获得一天的加班
					$DayDate['pcOTtime'] = intval($AllWorkOut[$date['emp_number']][@date("Ynj",$j)][9]['time']);
					$DayDate['WeekOTtime'] = intval($AllWorkOut[$date['emp_number']][@date("Ynj",$j)][10]['time']);
					$DayDate['HolidayOTtime'] = intval($AllWorkOut[$date['emp_number']][@date("Ynj",$j)][11]['time']);
					$DayDate['riqi'] = @date('Y-m-d',$j);
					$list[@date('Y-m-d',$j)."-".$DayDate['emp_number']] = $DayDate;
					//$list[date('Y-m-d',$j)."-".$date['emp_number']] = array('beizhu'=>"旷工",'LkuangGong'=>1,'riqi'=>date('Y-m-d',$j),'emp_firstname'=>$date['emp_firstname'],'emp_lastname'=>$date['emp_lastname']);
				}
			}
		}
		if($isGet == 1) return $list;
		$i = 0;
		$j = 0;
		//sort($list);
		$count = count($list);
		if($count > 0) {
			foreach ($list as $key => $val) {
				$i++;
				if($i <= $pageNO) continue;
				if($i > ($pageNO+$sysConst->itemsPerPage)) break;
				$newlist[$key] = $val;
				
				
			}
		}
		$records['list'] = $newlist;
		$records['pageNo'] = $pageNO;
		$records['Allcount'] = $count;
		
		$path = "/templates/attendance/ShowAttend_effectual.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}
	
	
	/**
	 *获取迟到早退旷工 
	 **/
	public function GetZaoTuiKuang($row,$StartWorkTime,$EndWorkTime,$Rule) {
		//判断还未到时间不算考勤
		if($StartWorkTime > time()) {
			return $row;
		}
		if(($row['starttime'] - $StartWorkTime > intval($Rule['yunXuLate']*60)) &&  ($row['starttime'] - $StartWorkTime <= intval($Rule['moreYunXuLate']*60))) {
			$row['later'] = 1;
			$row['laterHours'] = round(($row['starttime'] - $StartWorkTime)/3600,1);
			$row['beizhu'] = "迟到";
		//判断旷工
		} elseif(($row['starttime'] - $StartWorkTime > intval($Rule['moreYunXuLate']*60)) || $row['starttime'] == "") {
			$row['LkuangGong'] = 1;
			$row['beizhu'] = "旷工";
		}
		//判断早退
		if(($EndWorkTime - $row['endtime'] > intval($Rule['zaoTuiMinTime']*60)) && ($EndWorkTime - $row['endtime'] <= intval($Rule['moreZaoTuiMinTime']*60))) {
			$row['ZaoTui'] = 1;
			$row['laterHours'] = round(($EndWorkTime - $row['endtime'])/3600,1);
			if($row['LkuangGong'] != 1) {
				if($row['later'] == 1) {
					$row['beizhu'] = "迟到 - 早退";
				} else {
					$row['beizhu'] = "早退";
				}
			}
		//判断旷工
		} elseif(($EndWorkTime - $row['endtime'] > intval($Rule['moreZaoTuiMinTime']*60)) || $row['endtime'] == "") {
			$row['ZkuangGong'] = 1;
			$row['beizhu'] = "旷工";
		}
		return $row;
	}
	
	/**
	 *获取漏打卡，手签卡记录融入打卡记录里面 
	 **/
	public function GetSpAdRecord($record,$IsYouXiao="",$where_sp="") {
		$sql = "select a.Id,a.EmpId,a.Content,b.employee_id,b.work_station,b.emp_lastname,b.emp_firstname,b.emp_middle_name,b.emp_nick_name,a.TypeId,a.AddTime,a.StartTime,a.EndTime from hs_hr_emp_attendance_sp a left join hs_hr_employee b on b.emp_number = a.EmpId where a.IsCheck=1 {$where_sp} and a.TypeId in ({$this->AttendanceCache['SpStatType'][2]})";
		//echo $sql;die();
		$query = $this->db->executeQuery($sql);
		while ($rs = mysql_fetch_array($query, MYSQL_ASSOC)) {
			$rs['RecordTime'] = $rs['StartTime'];
			$rs['qian'] = 1;
			if($IsYouXiao == 1) {
				$record[] = $rs;
			} else {
				$record[$rs['EmpId']][@date("Y-n-j",$rs['StartTime'])][$rs['StartTime']] = $rs;
			}
		}
		return $record;
	}
	
	
	/**
	 *获取加班记录 $type 1:开始时间的所在的一天时间  2：考勤报表的获取数据
	 **/
	public function GetOutWordTIme($StartTime="",$EndTime="",$type="",$EmpId="") {
		$where = "";
		if($type==1) {
			$StartTime = strtotime(@date("Y-m-d",$StartTime)." 00:00:00");
			$EndTime = $StartTime+3600*24;
		}
		if($StartTime > 0) {
			$where .= " and a.StartTime>={$StartTime} ";
		}
		if($EndTime > 0) {
			$where .= " and a.EndTime<={$EndTime} ";
		}
		if($EmpId != "") {
			$where .= " and a.EmpId={$EmpId} ";
		}
		$record = array(); // SUM(a.hour) as dayhour
		$sql = "select a.EmpId,b.emp_lastname,b.emp_firstname,a.TypeId,a.StartTime,a.EndTime,a.hour from hs_hr_emp_attendance_sp a left join hs_hr_employee b on b.emp_number = a.EmpId  where a.IsCheck=1 and a.TypeId in ({$this->AttendanceCache['SpStatType'][3]}) {$where}";// group by a.EmpId,a.TypeId,FROM_UNIXTIME(a.StartTime,'%Y%m%d')
		$query = $this->db->executeQuery($sql);
		while ($rs = mysql_fetch_array($query, MYSQL_ASSOC)) {
			if($type==2) {
				$record[$rs['EmpId']][$rs['TypeId']]['time'] += $rs['hour'];
				$record[$rs['EmpId']][$rs['TypeId']]['num'] += 1;
			} else {
				$record[$rs['EmpId']][@date("Ynj",$rs['StartTime'])][$rs['TypeId']]['time'] += $rs['hour'];
				$record[$rs['EmpId']][@date("Ynj",$rs['StartTime'])][$rs['TypeId']]['num'] += 1;
				$record[$rs['EmpId']][@date("Ynj",$rs['StartTime'])]['getworktime'][] = $rs;
				
			}
		}
		return $record;
	}
	
	
	/**
	 *考勤排除特殊考勤 
	 **/
	public function RemoveSpAd($row,$StartWorkTime,$EndWorkTime) {
		//查询所有特殊考勤
		if($this->SpAdList == "") {
			$sql = "select a.Id,a.EmpId,b.emp_lastname,b.emp_firstname,b.emp_middle_name,b.emp_nick_name,a.TypeId,a.AddTime,a.StartTime,a.EndTime from hs_hr_emp_attendance_sp a left join hs_hr_employee b on b.emp_number = a.EmpId where a.IsCheck=1 and a.TypeId in ({$this->AttendanceCache['SpStatType'][1]},{$this->AttendanceCache['SpStatType'][3]}) ";
			$query = $this->db->executeQuery($sql);
			while ($rs = mysql_fetch_array($query, MYSQL_ASSOC)) {
				$this->SpAdList[$rs['EmpId']][] = $rs;
			}
		}
		
		$IsSpAd = false;
		//排除特殊考勤
			if(count($this->SpAdList[$row['emp_number']]) > 0) {
				foreach ($this->SpAdList[$row['emp_number']] as $key => $val) {
					//判断如果一天都是特殊考勤
					$row['info'] = $val;
					if(in_array($val['TypeId'], explode(",",$this->AttendanceCache['SpStatType'][3]))) {
						//如果是早上加班
						if($val['StartTime'] <= $StartWorkTime && $val['EndTime'] >= $StartWorkTime) {
							$row['starttime'] = $StartWorkTime;
						}
						//如果是下午加班
						if($val['StartTime'] <= $EndWorkTime && $val['EndTime'] >= $EndWorkTime) {
							$row['endtime'] = $EndWorkTime;
						}
					} elseif($val['StartTime'] <= $StartWorkTime && $val['EndTime'] >= $EndWorkTime) {
						$IsSpAd = true;
						break;
					//如果特殊考勤早上是，下午不是,下午是当天
					} elseif($val['StartTime'] <= $StartWorkTime && $val['EndTime'] < $EndWorkTime && @date("Y-m-d",$val['EndTime']) == @date("Y-m-d",$EndWorkTime)) {
						//首先判断开始开卡时间有没有在白名单时间结束之前
						if($row['starttime'] <= $val['EndTime']) {
							//比较打卡时间和白名单时间得出最晚时间
							if($val['EndTime'] > $row['endtime']) {
								$row['endtime'] = $val['EndTime'];
							}
							//比较打卡时间和规定上班时间得出最早时间
							if($StartWorkTime < $row['starttime']) {
								$row['starttime'] = $StartWorkTime;
							}
						} else {
							//计算中间迟到
							$row = $this->GetZaoTuiKuang($row,$val['EndTime'],$EndWorkTime,$this->RuleValue);
							$row['NoJisuan'] = 1;
						}
						break;
					//如果特殊考勤下午是，早上不是，早上是当天
					} elseif($val['StartTime'] > $StartWorkTime && $val['EndTime'] >= $EndWorkTime && @date("Y-m-d",$val['StartTime']) == @date("Y-m-d",$StartWorkTime)) {
						//首先判断开始开卡时间有没有在白名单时间
						if($val['StartTime'] <= $row['endtime']) {
							//比较打卡时间和特殊考勤时间得出最早时间
							if($val['StartTime'] < $row['starttime']) {
								$row['starttime'] = $val['StartTime'];
							}
							//比较打卡时间和下班时间得出最晚时间
							if($EndWorkTime > $row['endtime']) {
								$row['endtime'] = $EndWorkTime;
							}
						} else {
							//计算中间迟到
							$row = $this->GetZaoTuiKuang($row,$StartWorkTime,$val['StartTime'],$this->RuleValue);
							$row['NoJisuan'] = 1;
						}
						break;
					//如果特殊考勤在当天内而且在上班时间内
					} elseif($val['StartTime'] > $StartWorkTime && $val['EndTime'] < $EndWorkTime) {
						//比较打卡时间和白名单时间得出最早时间
						if($val['StartTime'] < $row['starttime']) {
							$row['starttime'] = $val['StartTime'];
						}
						//比较打卡时间和特殊考勤时间得出最晚时间
						if($val['EndTime'] > $row['endtime']) {
							$row['endtime'] = $val['EndTime'];
						}
						break;
					}
				}
			}
			return array('IsSpAd'=>$IsSpAd,'row'=>$row);
		
	}
	
	/**
	 *考勤排除周末 
	 **/
	public function RemoveWeek($row,$StartWorkTime,$EndWorkTime) {
		//获取周末和节假日
		if($this->WeekHolidays == "") {
			$AttendanceStatistics = new AttendanceStatistics();
			$this->WeekHolidays = $AttendanceStatistics->GetWeekAndHolidays();
		}
		if($this->RuleValue == "") {
        	$this->RuleValue = $this->getRuleValue();
        }
		//排除周末
		$IsWeek = false;
		$Weeks = $this->WeekHolidays['Week'][0];
		foreach ($Weeks as $key => $val) {
			if($val['num'] == 1) {
				if(@date('N',$StartWorkTime) == $val['day']) {
					$IsWeek = true;
					break;
				}
			} elseif($val['num'] == 0.5) {
				if(@date('N',$StartWorkTime) == $val['day']) {
					//周末半天假，算下午半天，早上上半天班
					$row = $this->GetZaoTuiKuang($row,$StartWorkTime,$EndWorkTime,$this->RuleValue);
					$row['NoJisuan'] = 1;
					break;
				}
			}
		}
		return array('IsWeek'=>$IsWeek,'row'=>$row);
	}
	
	/**
	 *考勤排除假节日
	 **/
	public function RemoveHoliday($row,$StartWorkTime,$EndWorkTime) {
		//获取周末和节假日
		if($this->WeekHolidays == "") {
			$AttendanceStatistics = new AttendanceStatistics();
			$this->WeekHolidays = $AttendanceStatistics->GetWeekAndHolidays();
		}
		if($this->RuleValue == "") {
        	$this->RuleValue = $this->getRuleValue();
        }
		//排除周末
		$IsHoliday = false;
		$Holidays = $this->WeekHolidays['Holidays'];
		foreach ($Holidays as $key => $val) {
			if($val['recurring'] == 1) {
				$Sstr = @date("md",$StartWorkTime);
				$Estr = @date("md",$EndWorkTime);
				$Dstr = @date("md",strtotime($val['date']));
				if($val['num'] == 1) {
					if(@date("md",$StartWorkTime) == @date("md",strtotime($val['date']))) {
						$IsHoliday = true;
						break;
					}
				} elseif($val['num'] == 0.5) {
					if(@date("md",$StartWorkTime) == @date("md",strtotime($val['date']))) {
						//周末半天假，算下午半天，早上上半天班
						$row = $this->GetZaoTuiKuang($row,$StartWorkTime,$EndWorkTime,$this->RuleValue);
						$row['NoJisuan'] = 1;
						break;
					}
				}
			}elseif($val['num'] == 1) {
				if(@date('Y-m-d',$StartWorkTime) == $val['date']) {
					$IsWeek = true;
					break;
				}
			} elseif($val['num'] == 0.5) {
				if(@date('Y-m-d',$StartWorkTime) == $val['date']) {
					//周末半天假，算下午半天，早上上半天班
					$row = $this->GetZaoTuiKuang($row,$StartWorkTime,$EndWorkTime,$this->RuleValue);
					$row['NoJisuan'] = 1;
					break;
				}
			}
		}
		return array('IsHoliday'=>$IsHoliday,'row'=>$row);
	}
	
	/**
	 *考勤排除白名单 
	 **/
	public function RemoveWhitelist($emp_number,$row,$StartWorkTime,$EndWorkTime) {
		//获取考勤白名单
		if($this->newwiletlist == "") {
			$this->wilteList = $this->ShowAttend_whitelist(1);
			if(count($this->wilteList) > 0) {
				foreach ($this->wilteList as $key => $val) {
					$this->newwiletlist[$val['emp_number']][] = $val;
				}
			}
		}
		
		if($this->RuleValue == "") {
        	$this->RuleValue = $this->getRuleValue();
        }

		$IsWhite = false;
		//排除考勤白名单
			if(count($this->newwiletlist[$emp_number]) > 0) {
				foreach ($this->newwiletlist[$emp_number] as $key => $val) {
					//判断如果一天都是白名单
					if($val['StartTime'] <= $StartWorkTime && $val['EndTime'] >= $EndWorkTime) {
						$IsWhite = true;
						break;
					//如果白名单早上是，下午不是,下午是当天
					} elseif($val['StartTime'] <= $StartWorkTime && $val['EndTime'] < $EndWorkTime && @date("Y-m-d",$val['EndTime']) == @date("Y-m-d",$EndWorkTime)) {
						//首先判断开始开卡时间有没有在白名单时间结束之前
						if($row['starttime'] <= $val['EndTime']) {
							//比较打卡时间和白名单时间得出最晚时间
							if($val['EndTime'] > $row['endtime']) {
								$row['endtime'] = $val['EndTime'];
							}
							//比较打卡时间和规定上班时间得出最早时间
							if($StartWorkTime < $row['starttime']) {
								$row['starttime'] = $StartWorkTime;
							}
						} else {
							//计算中间迟到
							$row = $this->GetZaoTuiKuang($row,$val['EndTime'],$EndWorkTime,$this->RuleValue);
							$row['NoJisuan'] = 1;
						}
						break;
					//如果白名单下午是，早上不是，早上是当天
					} elseif($val['StartTime'] > $StartWorkTime && $val['EndTime'] >= $EndWorkTime && @date("Y-m-d",$val['StartTime']) == @date("Y-m-d",$StartWorkTime)) {
						//首先判断开始开卡时间有没有在白名单时间
						if($val['StartTime'] <= $row['endtime']) {
							//比较打卡时间和白名单时间得出最早时间
							if($val['StartTime'] < $row['starttime']) {
								$row['starttime'] = $val['StartTime'];
							}
							//比较打卡时间和下班时间得出最晚时间
							if($EndWorkTime > $row['endtime']) {
								$row['endtime'] = $EndWorkTime;
							}
						} else {
							//计算中间迟到
							$row = $this->GetZaoTuiKuang($row,$StartWorkTime,$val['StartTime'],$this->RuleValue);
							$row['NoJisuan'] = 1;
						}
						break;
					//如果白名单在当天内而且在上班时间内
					} elseif($val['StartTime'] > $StartWorkTime && $val['EndTime'] < $EndWorkTime) {
						//比较打卡时间和白名单时间得出最早时间
						if($val['StartTime'] < $row['starttime']) {
							$row['starttime'] = $val['StartTime'];
						}
						//比较打卡时间和白名单时间得出最晚时间
						if($val['EndTime'] > $row['endtime']) {
							$row['endtime'] = $val['EndTime'];
						}
						break;
					}
				}
			}
			return array('IsWhite'=>$IsWhite,'row'=>$row);
	}

	
	/**
	 *考勤白名单记录 
	 **/
	public function ShowAttend_whitelist($isGet="",$code="",$name="") {
		$sysConst = new sysConf();
		$where = "Where 1=1 ";
		$where .= $this->GetSearchSlqWhere($code,$name);
        $limit = "";
        $list = array();
		$pageNO = isset($_POST['pageNO'])?intval($_POST['pageNO']):1;
        if ($pageNO > 0) {
            $pageNO--;
            $pageNO *= $sysConst->itemsPerPage;

            $limit = " limit {$pageNO}, {$sysConst->itemsPerPage}";
        }
        if($isGet == 1) $limit="";
		$sql = "select count(*) as allcount from hs_hr_emp_ad_whitelist a left join hs_hr_employee b on b.emp_number = a.EmpId {$where}";
		$query = $this->db->executeQuery($sql);
		$Allcount = mysql_fetch_array($query, MYSQL_ASSOC);
		
		$sql = "select a.Id,b.employee_id,b.emp_lastname,b.emp_firstname,b.emp_middle_name,b.emp_nick_name,a.StartTime,a.EndTime,a.AddTime from hs_hr_emp_ad_whitelist a left join hs_hr_employee b on b.emp_number = a.EmpId {$where} {$limit}";
		$query = $this->db->executeQuery($sql);
		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			$list[] = $row;
		}
		if($isGet == 1) return $list;
		$records['list'] = $list;
		$records['pageNo'] = $pageNO;
		$records['Allcount'] = $Allcount['allcount'];
		$path = "/templates/attendance/ShowAttend_whitelist.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}
	
	/**
	 *获取单条考勤白名单记录 
	 **/
	public function AddAttend_whitelist($Id="") {
		if($Id > 0) {
		$sql = "select a.Id,a.EmpId,b.employee_id,b.emp_lastname,b.emp_firstname,b.emp_middle_name,b.emp_nick_name,a.AddTime,a.StartTime,a.EndTime from hs_hr_emp_ad_whitelist a left join hs_hr_employee b on b.emp_number = a.EmpId where a.Id={$Id}";
		$query = $this->db->executeQuery($sql);
		$records = mysql_fetch_array($query, MYSQL_ASSOC);
		} else {
			$records = array();
		}
		$path = "/templates/attendance/AddAttend_white.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}


	/**
	 *保存考勤白名单记录 
	 **/
	public function SaveAttend_white($Id="") {
		$EmpId = intval($_POST["EmpId"]);
		$StartTime = strtotime($_POST["StartTime"]." ".intval($_POST["StartTime_hour"]).":".intval($_POST["StartTime_min"]).":00");
		$EndTime = strtotime($_POST["EndTime"]." ".intval($_POST["EndTime_hour"]).":".intval($_POST["EndTime_min"]).":00");
		if($Id > 0) {
			$sql = "update hs_hr_emp_ad_whitelist set EmpId = {$EmpId},StartTime = {$StartTime},EndTime = {$EndTime}  where Id={$Id}";
			if($this->db->executeQuery($sql)) {
				$this->redirect("保存成功", "?adcode=whitelist");
			} else {
				$this->redirect("保存失败", "?adcode=whitelist");
			}
		} else {
			$sql = "insert into hs_hr_emp_ad_whitelist (EmpId,StartTime,EndTime,AddTime) values ($EmpId,$StartTime,$EndTime,".time().")";
			if($this->db->executeQuery($sql)) {
				$this->redirect("添加成功", "?adcode=whitelist");
			} else {
				$this->redirect("添加失败", "?adcode=whitelist");
			}
		}
	}
	
	/**
	 *删除白名单数据记录 
	 **/
	public function DelAttend_white() {
		
		$EmpIdStr = implode(',',$_POST["chkLocID"]);
		$sql = "delete from hs_hr_emp_ad_whitelist where Id in ({$EmpIdStr})";
		//echo $sql;die();
		if($this->db->executeQuery($sql)) {
			$this->redirect("删除成功", "?adcode=whitelist");
		} else {
			$this->redirect("删除失败", "?adcode=whitelist");
		}
		
	}
	
	/**
	 *获取搜索的sqlwhere 
	 **/
	public function GetSearchSlqWhere($code="",$name="") {
		$where = "";
		$loc_code = isset($_POST['loc_code'])?htmlspecialchars(trim($_POST['loc_code'])):"";
		$loc_name = isset($_POST['loc_name'])?htmlspecialchars(trim($_POST['loc_name'])):"";
		if($code != "") $loc_code = $code;
		if($name != "") $loc_name = $name;
		if($loc_name != "") {
			if($loc_name == "emp_firstname") {
				$where .= " and {$loc_code} like '%{$loc_name}%' ";
			} else {
				$where .= " and {$loc_code} = '{$loc_name}' ";
			}
		}
		return $where;
	}
	
	/**
	 *特别考勤记录 
	 **/
	public function ShowSpecialAttend($typeId=0) {
		$sysConst = new sysConf();
		$where = "Where 1=1 ";
		$where .= $this->GetSearchSlqWhere();
		if($typeId == 0) {
			$where .= " and a.TypeId in ({$this->AttendanceCache['SpStatType'][1]})";
			$records['title'] = "请假";
		} elseif($typeId == 9) {
			$where .= " and a.TypeId in ({$this->AttendanceCache['SpStatType'][3]})";
			$records['title'] = "加班";
		} else {
			$where .= " and a.TypeId = {$typeId}";
			$records['title'] = $this->AttendanceCache['SpecialAdType'][$typeId];
		}

		$Year = intval($_REQUEST['Year']);
		$Month = intval($_REQUEST['Month']);
		if($Year > 0 && $Month > 0) {
			/*$Year = date("Y");
			$Month = intval(date("m"));*/
			$where .= " and FROM_UNIXTIME(StartTime,'%Y%c')='".$Year.$Month."' ";
		}

        $limit = "";
        $list = array();
		$pageNO = isset($_POST['pageNO'])?intval($_POST['pageNO']):1;
        if ($pageNO > 0) {
            $pageNO--;
            $pageNO *= $sysConst->itemsPerPage;

            $limit = " limit {$pageNO}, {$sysConst->itemsPerPage}";
        }

		$sql = "select count(*) as allcount from hs_hr_emp_attendance_sp a left join hs_hr_employee b on b.emp_number = a.EmpId {$where}";
		$query = $this->db->executeQuery($sql);
		$Allcount = mysql_fetch_array($query, MYSQL_ASSOC);
		
		$sql = "select a.Id,a.hour,b.employee_id,b.emp_lastname,b.emp_firstname,b.emp_middle_name,b.emp_nick_name,a.TypeId,a.AddTime,a.StartTime,a.EndTime from hs_hr_emp_attendance_sp a left join hs_hr_employee b on b.emp_number = a.EmpId {$where} {$limit}";
		$query = $this->db->executeQuery($sql);

		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			$row['TypeName'] = $this->AttendanceCache['SpecialAdType'][$row['TypeId']];
			if(in_array($row['TypeId'],explode(',',$this->AttendanceCache['SpStatType'][3]))) {
				$row['LongTime'] = $row['hour'];
			} else {
				$row['LongTime'] = round(($row['EndTime'] - $row['StartTime'])/3600,1);
			}
			$list[] = $row;
		}
		//print_r($sql);
		//die();
		$records['list'] = $list;
		$records['pageNo'] = $pageNO;
		$records['Allcount'] = $Allcount['allcount'];
		$path = "/templates/attendance/ShowSpecialAttend.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}
	
	
	/**
	 *显示或添加特别考勤单个记录 
	 **/
	public function AddSpecialAttend($Id="") {
		
		if($Id > 0) {
		$sql = "select a.Id,a.EmpId,a.Content,a.hour,b.employee_id,b.emp_lastname,b.emp_firstname,b.emp_middle_name,b.emp_nick_name,a.TypeId,a.AddTime,a.StartTime,a.EndTime from hs_hr_emp_attendance_sp a left join hs_hr_employee b on b.emp_number = a.EmpId where a.Id={$Id}";
		$query = $this->db->executeQuery($sql);

		$records = mysql_fetch_array($query, MYSQL_ASSOC);
		$records['TypeName'] = $this->AttendanceCache['SpecialAdType'][$records['TypeId']];
		
		} else {
			$records = array();
		}
		$records['typelist'] = $this->AttendanceCache['SpecialAdType'];
		/*print_r($records);
		die();*/
		$records['ResidualHours'] = $this->getResidualHours();
		$path = "/templates/attendance/AddSpecialAttend.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}
	
	
	/**
	 *保存特别考勤单个记录 
	 **/
	public function SaveSpecialAttend($Id="") {
		
		$EmpId = intval($_POST["EmpId"]);
		$AdType = intval($_POST["AdType"]);
		$Content = $_POST["Content"];
		$StartTime = strtotime($_POST["StartTime"]." ".intval($_POST["StartTime_hour"]).":".intval($_POST["StartTime_min"]).":00");
		$EndTime = strtotime($_POST["EndTime"]." ".intval($_POST["EndTime_hour"]).":".intval($_POST["EndTime_min"]).":00");
		if($StartTime >= $EndTime) {
			$this->redirect("开始日期不能大于结束日期", "?adcode=special_attend");

		} else {
			$hour = floatval($_POST['hour']);
			if($Id > 0) {
				$sql = "update hs_hr_emp_attendance_sp set EmpId = {$EmpId},TypeId = {$AdType},Content = '{$Content}',StartTime = {$StartTime},EndTime = {$EndTime},hour='{$hour}'  where Id={$Id}";
				if($this->db->executeQuery($sql)) {
					$this->redirect("保存成功", "?adcode=special_attend&typeid={$AdType}");
				} else {
					$this->redirect("保存失败", "?adcode=special_attend&typeid={$AdType}");
				}
			} else {
				$sql = "insert into hs_hr_emp_attendance_sp (EmpId,TypeId,Content,StartTime,EndTime,hour,AddTime) values ({$EmpId},{$AdType},'{$Content}',{$StartTime},{$EndTime},'{$hour}',".time().")";
				//echo $sql;
				//die();
				if($this->db->executeQuery($sql)) {
					$this->redirect("添加成功", "?adcode=special_attend&typeid={$AdType}");
				} else {
					$this->redirect("添加失败", "?adcode=special_attend&typeid={$AdType}");
				}
			}
		}
	}
	
	
	/**
	 *删除特别考勤数据记录 
	 **/
	public function DelSpecialAttend() {
		
		$EmpIdStr = implode(',',$_POST["chkLocID"]);
		$sql = "delete from hs_hr_emp_attendance_sp where Id in ({$EmpIdStr})";
		if($this->db->executeQuery($sql)) {
			$this->redirect("删除成功", "?adcode=special_attend");
		} else {
			$this->redirect("删除失败", "?adcode=special_attend");
		}
		
	}
	
	
	/**
	 *获取员工名字和id
	 **/
	public function GetEmpName() {
		
		$EmpName = $_POST['EmpName'];
		$tbname = $_POST['tbname'];
		$EmpNameId = $_POST['EmpNameId'];
		$div = $_POST['div'];
		$EmpIdId = $_POST['EmpIdId'];
		$sql = "select * from  hs_hr_employee  where emp_firstname like '%{$EmpName}%' or employee_id like '%{$EmpName}%'";
		//echo $sql;
		//die();
		$query = $this->db->executeQuery($sql);
		
		$str ='<tr style="cursor:default" onmousemove="$(this).css(\'background\-color\',\'#FFCCFF\')" onmouseout="$(this).css(\'background\-color\',\'\')"><td center="left" onclick="$(\'#'.$_POST["div"].'\').hide();">关闭</td></tr>';
        
		while($records = mysql_fetch_array($query, MYSQL_ASSOC))
	    {
	    	$records["emp_firstname2"] = str_replace($EmpName,'<font color=red>'.$EmpName.'</font>',$records["emp_firstname"]);
	    	$records["employee_id2"] = str_replace($EmpName,'<font color=red>'.$EmpName.'</font>',$records["employee_id"]);
	    	$str .= '<tr style="cursor:default" onmousemove="$(this).css(\'background\-color\',\'#FFCCFF\')" onmouseout="$(this).css(\'background\-color\',\'\')"><td center="left" onclick="showproname(\''.$records["emp_firstname"].'\',\''.$records["emp_number"].'\',\''.$EmpIdId.'\',\''.$EmpNameId.'\',\''.$div.'\');">'.$records["emp_firstname2"].'('.$records["employee_id2"].')</td></tr>';
	    }
	    if ($str != "")
	    {
	    	echo $str;
	    }
	    else {
	    	echo "no";
	    }
	    exit;
	}
	
	
	/**
	 *查看考勤月度表 
	 **/
	public function ShowAttendanceReport($type = "Month",$UserId='') {
		$sysConst = new sysConf();
		$ReportTitleArr =  array('Month'=>'月度考勤','Quarter'=>'季度考勤','Year'=>'年度考勤');
		$ReportId =  array('Month'=>0,'Quarter'=>1,'Year'=>2);
		$where = "Where 1=1 ";
		if($_SESSION['isAdmin'] != "Yes") {
			$UserId = intval($_SESSION['empID']);
		}
		if($UserId > 0) {
			$where .= " and emp_number = {$UserId} ";
		}
		$where .= $this->GetSearchSlqWhere();
        $limit = "";
        $list = array();
		$pageNO = isset($_POST['pageNO'])?intval($_POST['pageNO']):1;
        if ($pageNO > 0) {
            $pageNO--;
            $pageNO *= $sysConst->itemsPerPage;

            $limit = " limit {$pageNO}, {$sysConst->itemsPerPage}";
        }
        
		$sql = "select count(*) as allcount from hs_hr_employee {$where}";
		$query = $this->db->executeQuery($sql);
		$Allcount = mysql_fetch_array($query, MYSQL_ASSOC);
		
		$sql = "select joined_date,work_station,emp_number,employee_id,emp_lastname,emp_firstname,emp_middle_name,emp_nick_name from hs_hr_employee {$where} {$limit}";
		
		$query = $this->db->executeQuery($sql);
		$AttendanceStatistics = new AttendanceStatistics();
		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			$row['isOnWork'] = "在职";
			if($row['joined_date'] == "") $row['isOnWork'] = "离职";
			$nowtime = time();
			//如果是月份
			if($ReportId[$type] == 0) {
				if(intval($_REQUEST['Year']) > 0 && intval($_REQUEST['Month']) > 0) {
					$GetYear = intval($_REQUEST['Year']);
					$GetMonth = intval($_REQUEST['Month']);
				} else {
					$GetYear = @date("Y");
					$GetMonth = @date("m");
				}
				
				//for ($j = strtotime($row['joined_date']); $j <=$nowtime;$j = mktime(0, 0, 0, date("m",$j)+1, 1, date("Y",$j))) {
					$row['riqi'] = $GetYear."年-".$GetMonth."月";//date("Y-m",$j);
					$row['crtype'] = $ReportId[$type];
					$row['cryear'] = $GetYear;//date("Y",$j);
					$row['crotherd'] = $GetMonth;//date("m",$j);
					$ReportRow = $this->CheckReportAndGet($row['emp_number'],$row['crtype'],$row['cryear'],$row['crotherd']);
					if($ReportRow != "") {
						$row = array_merge($row,$ReportRow);
						$row['IsRecord'] = 1;
					} else {
						$row = $this->GetReportDate($AttendanceStatistics,$row,$ReportId[$type],array($row['cryear'],$row['crotherd']));
						$row['IsRecord'] = 0;
					}
					$list[] = $row;
				//}
			} elseif ($ReportId[$type] == 1) {
				$MonJidu = array(1=>array(1,3),2=>array(4,6),3=>array(7,9),4=>array(10,12));
				$MonJiduDuiY = array(1=>1,4=>2,7=>3,10=>4);
				
				if(intval($_REQUEST['Year']) > 0 && intval($_REQUEST['Jidu']) > 0) {
					$GetYear = intval($_REQUEST['Year']);
					$jidu = intval($_REQUEST['Jidu']);
				} else {
					$GetYear = @date("Y");
					//得出入职是第几季度
					//$Month = date("m",strtotime($row['joined_date']));
					$Month = @date("m");
					$jidu = "";
					foreach ($MonJidu as $key => $val) {
						if($val[0] <= $Month) {
							$jidu = $key;
						}
					}
				}
				//for ($j = mktime(0, 0, 0, $MonJidu[$jidu][0], 1, date("Y")); $j <=$nowtime;$j = mktime(0, 0, 0, date("m",$j)+3, 1, date("Y"))) {
					//$row['riqi'] = date("Y",$j)."年-第{$MonJiduDuiY[date("n",$j)]}季度";
					$row['riqi'] = $GetYear."年-第{$jidu}季度";
					$row['crtype'] = $ReportId[$type];
					$row['cryear'] = $GetYear;//date("Y",$j);
					$row['crotherd'] = $jidu;//$MonJiduDuiY[date("n",$j)];
					$ReportRow = $this->CheckReportAndGet($row['emp_number'],$row['crtype'],$row['cryear'],$row['crotherd']);
					if($ReportRow != "") {
						$row = array_merge($row,$ReportRow);
						$row['IsRecord'] = 1;
					} else {
						$row = $this->GetReportDate($AttendanceStatistics,$row,$ReportId[$type],array($row['cryear'],$row['crotherd']));
						$row['IsRecord'] = 0;
					}
					$list[] = $row;
				//}
			} else {
				if(intval($_REQUEST['Year']) > 0) {
					$GetYear = intval($_REQUEST['Year']);
				} else {
					$GetYear = @date("Y");
				}
				//for ($j = strtotime($row['joined_date']); $j <=$nowtime;$j = mktime(0, 0, 0, 1, 1, date("Y",$j)+1)) {
					$row['riqi'] = $GetYear."年";//date("Y",$j);
					$row['crtype'] = $ReportId[$type];
					$row['cryear'] = $GetYear;//date("Y",$j);
					$row['crotherd'] = "";
					$ReportRow = $this->CheckReportAndGet($row['emp_number'],$row['crtype'],$row['cryear'],$row['crotherd']);
					if($ReportRow != "") {
						$row = array_merge($row,$ReportRow);
						$row['IsRecord'] = 1;
					} else {
						$row = $this->GetReportDate($AttendanceStatistics,$row,$ReportId[$type],$row['cryear']);
						$row['IsRecord'] = 0;
					}
					$list[] = $row;
				//}
			}
		}
		$records['list'] = $list;
		$records['pageNo'] = $pageNO;
		$records['Allcount'] = $Allcount['allcount'];
		$records['Title'] = $ReportTitleArr[$type];
		$records['action'] = $type;

		$path = "/templates/attendance/ShowAttendanceReport.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}
	
	/**
	 *用于月，季度，年度的统计假期的查询 
	 **/
	public function GetReportDate($AttendanceStatistics,$row,$type="",$riqi="") {
		$date = $AttendanceStatistics->StatisticsSpAttendance($row['emp_number'],$this->AttendanceCache['SpStatType'][1],$type,$riqi);
		//事假
		$row['shijia'] = $date['TimeInfo'][$row['emp_number']][1]; //$AttendanceStatistics->StatisticsSpAttendance($row['emp_number'],1,$type,$riqi);
		$row['shijia']['time'] = intval($date['TimeInfo'][$row['emp_number']][1]['hour']);//intval(intval($row['shijia']['time']/3600)/24);
		//病假
		$row['bingjia'] = $date['TimeInfo'][$row['emp_number']][2];//$AttendanceStatistics->StatisticsSpAttendance($row['emp_number'],2,$type,$riqi);
		$row['bingjia']['time'] = intval($date['TimeInfo'][$row['emp_number']][2]['hour']);//intval(intval($row['bingjia']['time']/3600)/24);
		
		//年假
		$row['nianjia'] = $date['TimeInfo'][$row['emp_number']][3];
		$row['nianjia']['time'] = intval($date['TimeInfo'][$row['emp_number']][3]['hour']);//intval(intval($row['nianjia']['time']/3600)/24);
		
		//婚假
		$row['hunjia'] = $date['TimeInfo'][$row['emp_number']][4];
		$row['hunjia']['time'] = intval($date['TimeInfo'][$row['emp_number']][4]['hour']);//intval(intval($row['hunjia']['time']/3600)/24);
		
		//丧假
		$row['sangjia'] = $date['TimeInfo'][$row['emp_number']][5];
		$row['sangjia']['time'] = intval($date['TimeInfo'][$row['emp_number']][5]['hour']);//intval(intval($row['sangjia']['time']/3600)/24);
		
		//产假
		$row['chanjia'] = $date['TimeInfo'][$row['emp_number']][6];
		$row['chanjia']['time'] = intval($date['TimeInfo'][$row['emp_number']][6]['hour']);//intval(intval($row['chanjia']['time']/3600)/24);
		
		//临换
		$row['linhuan'] = $date['TimeInfo'][$row['emp_number']][7];
		$row['linhuan']['time'] = intval($date['TimeInfo'][$row['emp_number']][7]['hour']);//intval(intval($row['linhuan']['time']/3600)/24);
		
		//外勤
		$row['waiqin'] = $date['TimeInfo'][$row['emp_number']][8];
		$row['waiqin']['time'] = intval($date['TimeInfo'][$row['emp_number']][8]['hour']);//intval(intval($row['waiqin']['time']/3600)/24);
		if($this->StatOt[$row['riqi']] == "") {
			$this->StatOt[$row['riqi']] = $AttendanceStatistics->StatisticsWorkOut($type,$riqi);
		}
		//平时加班
		$row['psjiaban']['num'] = $this->StatOt[$row['riqi']][$row['emp_number']][9]['num'];
		$row['psjiaban']['time'] = floatval($this->StatOt[$row['riqi']][$row['emp_number']][9]['time']);
		
		//周末加班
		$row['weekjiaban']['num'] = $this->StatOt[$row['riqi']][$row['emp_number']][10]['num'];
		$row['weekjiaban']['time'] = floatval($this->StatOt[$row['riqi']][$row['emp_number']][10]['time']);
		
		//节假日加班
		$row['holidayjiaban']['num'] = $this->StatOt[$row['riqi']][$row['emp_number']][11]['num'];
		$row['holidayjiaban']['time'] = floatval($this->StatOt[$row['riqi']][$row['emp_number']][11]['time']);
		
		if($this->Statczt[$row['riqi']] == "") {
			$this->Statczt[$row['riqi']] = $AttendanceStatistics->StatisticsLaterTui($type,$riqi);
		}
		$row['later'] = $this->Statczt[$row['riqi']][$row['emp_number']]['later'];
		$row['ZaoTui'] = $this->Statczt[$row['riqi']][$row['emp_number']]['ZaoTui'];
		$row['kuangGong'] = $this->Statczt[$row['riqi']][$row['emp_number']]['kuangGong'];
		$row['WorkHours'] = round($this->Statczt[$row['riqi']][$row['emp_number']]['WorkHours'],1);
		$row['NeedWorkHours'] = round($this->Statczt[$row['riqi']][$row['emp_number']]['NeedWorkHours'],1);
		$row['yeban'] = $this->Statczt[$row['riqi']][$row['emp_number']]['yeban'];
		return $row;
	}
	
	/**
	 * 生成月报表，季度报表
	 **/
	function CreateAttendanceReport() {
		$emp_number = $_GET['emp_number'];
		$crtype = $_GET['crtype'];
		$cryear = $_GET['cryear'];
		$crotherd = $_GET['crotherd'];
		$ReportId =  array(0=>'Month',1=>'Quarter',2=>'Year');
		$row['emp_number'] = $emp_number;
		//判断如果之前记录了就不要插入了
		if($this->CheckReportAndGet($emp_number,$crtype,$cryear,$crotherd) != "") {
			$this->redirect("已有数据不能生成", "?adcode=report&action=".$ReportId[$crtype]);
		}
		$AttendanceStatistics = new AttendanceStatistics();
		if($crtype == 0) {
			$row = $this->GetReportDate($AttendanceStatistics,$row,$crtype,array($cryear,$crotherd));
		} elseif($crtype == 1) {
			$row = $this->GetReportDate($AttendanceStatistics,$row,$crtype,array($cryear,$crotherd));
		} else {
			$row = $this->GetReportDate($AttendanceStatistics,$row,$crtype,$cryear);
		}
		if($crotherd != "") {
			$DateStr = $cryear."-".$crotherd;
		} else {
			$DateStr = $cryear;
		}
		$date = serialize($row);
		$sql = "insert into hs_hr_emp_attendance_stat (EmpId,StatType,DateStr,Content,AddTime) values ({$emp_number},{$crtype},'{$DateStr}','{$date}',".time().")";
		$this->db->executeQuery($sql);
		
		$this->redirect("生成成功", "?adcode=report&action=".$ReportId[$crtype]);
	}
	
	
	
	/**
	 * 或者报表的数据看看是不是已经生成了
	 **/
	function CheckReportAndGet($emp_number,$crtype,$cryear,$crotherd="") {

		if($crotherd == "") {
			$DateStr = $cryear;
		} else {
			$DateStr = $cryear."-".$crotherd;
		}
		$sql = "select EmpId,StatType,DateStr,Content from hs_hr_emp_attendance_stat where EmpId = {$emp_number} and StatType={$crtype} and DateStr='{$DateStr}'";
		$query = $this->db->executeQuery($sql);
		$result = mysql_fetch_array($query, MYSQL_ASSOC);
		if($result['EmpId'] != "") {
			return unserialize($result['Content']);
			//return "";
		} else {
			return "";
		}
	}
	
	/*
	 * 读取年假,需要判断是否在有效期内
	* */
	 function getResidualHours(){
		$reslut = 0;
		$sql = "select ResidualHours,EffectDate,EndDate from hs_hr_emp_annualleave  where EmpId ='{$this->emp_number}' ";
		$query = $this->db->executeQuery ( $sql );
		$row = mysql_fetch_array ( $query, MYSQL_ASSOC );
		if (is_array ( $row )) {
			$EffectDate = strtotime($row['EffectDate']." 00:00:00");
			$EndDate = strtotime($row['EndDate']." 23:59:59");
				
			if($EffectDate < time() && time() < $EndDate){
				$reslut = $row ['ResidualHours'];
			}
		}
		return array(
				'jiaqi'=>$reslut,
				'EffectDate'=>date('Y年m月d日',$EffectDate)." 00:00:00",
				'EndDate'=>date('Y年m月d日',$EndDate)." 23:59:59"
		);
	
	}
	
	
	
	private function _redirectToTimesheet($timesheetId, $message) {
		$this->redirect($message, "?timecode=Time&action=View_Timesheet&id={$timesheetId}");
	}


	public function redirect($message=null, $url = null) {

		if (isset($url)) {
			$mes = "";
			if (isset($message)) {
				$mes = "&message=";
			}
			$url=array($url.$mes);
			$id="";
		} else if (isset($message)) {
			preg_replace('/[&|?]+id=[A-Za-z0-9]*/', "", $_SERVER['HTTP_REFERER']);

			if (preg_match('/&/', $_SERVER['HTTP_REFERER']) > 0) {
				$message = "&message=".$message;
				$url = preg_split('/(&||\?)message=[A-Za-z0-9]*/', $_SERVER['HTTP_REFERER']);
			} else {
				$message = "?message=".$message;
			}

			if (isset($_REQUEST['id']) && !empty($_REQUEST['id']) && !is_array($_REQUEST['id'])) {
				$id = "&id=".$_REQUEST['id'];
			} else {
				$id="";
			}
		} else {
			if (isset($_REQUEST['id']) && !empty($_REQUEST['id']) && (preg_match('/&/', $_SERVER['HTTP_REFERER']) > 0)) {
				$id = "&id=".$_REQUEST['id'];
			} else if (preg_match('/&/', $_SERVER['HTTP_REFERER']) == 0){
				$id = "?id=".$_REQUEST['id'];
			} else {
				$id="";
			}
		}
		
		header("Location: ".$url[0].$message.$id);
	}
}
?>
